<!--
 * @Author: HeAo
 * @Date: 2021-10-14 09:15:54
 * @LastEditTime: 2021-10-14 10:00:03
 * @LastEditors: HeAo
 * @Description: 
 * @FilePath: \web2103-2105\web2105\3-2-Vue\day06\1-vuex基础使用.html
 * 别乱动！
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="../js/vue.js"></script>
  <script src="../js/vuex.js"></script>
</head>

<body>
  <div id="app">
    <h3>{{data1}}</h3>
    <h4>vuex-msg:{{msg}}</h4>
    <h5>vuex-users:{{users}}</h5>
    <h6>vuex-getters:{{upperMsg}}</h6>
  </div>
  <script>
    // 1.声明状态机Vuex实例
    let store = new Vuex.Store({
      state: {
        // 用来存放状态机中的数据
        msg: 'hello vuex',
        users: []
      },
      getters: {
        upperMsg(state) {
          return state.msg.toUpperCase()
        }
      },
      mutations: {
        // 突变，修改state中数据的唯一方法
        SET_MSG(state, payload) {
          state.msg = payload
        },
        SET_USERS(state, payload) {
          state.users = payload
        }
      },
      actions: {
        // 动作，存储异步方法的地方
        async findAllUser(context) {
          // let res = await 
          let res = {
            status: 200,
            message: '查询成功',
            data: [
              { id: 1, username: 'admin' },
              { id: 2, username: 'teacher' },
              { id: 3, username: 'student' },
            ],
            timestamp: 1634174703878
          }
          console.log(context);
          context.commit('SET_USERS', res.data)
        }
      }
    })

    let vm = new Vue({
      el: '#app',
      data: {
        data1: 'vue data'
      },
      computed: {
        // vuex中state里的数据，可以在vue实例的计算属性中直接获取
        msg() {
          return this.$store.state.msg
        },
        users() {
          return this.$store.state.users
        },
        upperData1() {
          // VUE DATA
          return this.data1.toUpperCase()
        },
        upperMsg() {
          return this.$store.getters.upperMsg
        }
      },
      methods: {},
      created() {
        // $store是注入进实例的状态机
        // dispatch是状态机中专门用来分发动作的一个函数
        this.$store.dispatch('findAllUser')
      },
      store
    })
  </script>
</body>

</html>